<template>
  <div>
    <div>
      <div style="width: 100%;">
        <h1>匿名聊天</h1>
        <el-form @submit.native.prevent :inline="true" class="demo-form-inline">
          <el-form-item label="消息">
            <el-input @keydown.enter.native="send" v-model="mess" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="send">发消息</el-button>
          </el-form-item>
        </el-form>
      </div>
      </div>


    <div style="margin-top: 2%;">
      <ul class="messages">
        <li class="message" v-for="(item, index) in toMessage" :key="index">
          <el-link
            style="font-size: 20px"
            :class="item.id == iMessage ? 's' : 's1'"
            type="success"
            disabled
            ><span v-html="$xss(item.mess)"></span
          ></el-link>
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      path: "ws://www.makamaka.top:19081/imserver/",
      socket: "",
      mess: "",
      toMessage: [],
      iMessage: [],
      timeId: null,
    };
  },
  mounted() {
    // 初始化
    this.init();
  },
  methods: {
    exit() {
      this.$router.push("/test1");
    },
    init: function () {
      if (typeof WebSocket === "undefined") {
        this.$message({
          message: "您的浏览器不支持",
          type: "warning",
        });
      } else {
        this.iMessage = Math.ceil(Math.random() * 100);
        // 实例化socket
        this.socket = new WebSocket(this.path + this.iMessage);
        // 监听socket连接
        this.socket.onopen = this.open;
        // 监听socket错误信息
        this.socket.onerror = this.error;
        // 监听socket消息
        this.socket.onmessage = this.getMessage;
      }
    },
    open: function () {
      console.log("socket连接成功");
    },
    error: function () {
      console.log("连接错误");
    },
    getMessage: function (msg) {
      this.toMessage.unshift(JSON.parse(msg.data));
    },
    send: function () {
      if (this.mess === "") {
        this.$message({
          message: "发送信息不能为空!",
          type: "warning",
        });
        return;
      }
      if (this.timeId) {
        this.$message({
          message: "您发送信息的速度太快了,喝杯茶休息一下吧",
          type: "warning",
        });
        return;
      }
      this.timeId = setTimeout(() => {
        this.timeId = null;
      }, 1000);
      this.socket.send(this.mess);
      this.mess = "";
    },
    close: function () {
      console.log("socket已经关闭");
    },
  },
  destroyed() {
    // 销毁监听
    this.socket.onclose = this.close;
  },
};
</script>

<style >
  ul{
    list-style: none
  }
/*.messages*/
/*  max-height: calc(100vh - 200px)*/
/*  overflow: auto*/
/*  .message*/
/*    */
.s{
  margin-left: 30%;
  margin-bottom: 1%;
}

.s1{
  margin-bottom: 1%;
  margin-right: 40%
}


</style>
